package com.lottery.im.module.chat.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.OnClick;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.fondesa.recyclerviewdivider.RecyclerViewDivider;
import com.lottery.im.MyApplication;
import com.lottery.im.R;
import com.lottery.im.api.Api;
import com.lottery.im.api.result.entity.MemberVipInfo;
import com.lottery.im.api.result.entity.OtherUserInfo;
import com.lottery.im.api.result.entity.SectionMemberVipInfo;
import com.lottery.im.base.BaseSwipeFragment;
import com.lottery.im.module.chat.adapter.SelectMemberVipAdapter;
import com.lottery.im.module.chat.presenter.MemberVipPresenter;
import com.lottery.im.module.chat.view.MemberVipView;
import com.lottery.im.module.setting.ui.ProfileFragment;
import com.lottery.im.util.DateUtils;
import com.lottery.im.util.StatusBarHelper;
import com.tencent.imsdk.TIMGroupMemberInfo;
import com.tencent.imsdk.TIMGroupMemberRoleType;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 群成员VIP等级情况
 */
public class MemberVipFragment extends BaseSwipeFragment<MemberVipPresenter>
    implements MemberVipView {

  private final static String ID_KEY = "ID_KEY";

  public static MemberVipFragment create(String id) {
    MemberVipFragment fragment = new MemberVipFragment();
    Bundle b = new Bundle();
    b.putString(ID_KEY, id);
    fragment.setArguments(b);
    return fragment;
  }

  @BindView(R.id.tv_title) TextView mTvTitle;
  @BindView(R.id.list) RecyclerView mList;

  private String mIdentify;

  // 包含分组头部
  private List<SectionMemberVipInfo> mSectionMemberVipInfos;
  // 不包含分组头部
  private List<SectionMemberVipInfo> mMemberVipInfos;
  private SelectMemberVipAdapter mAdapter;

  private final static int PROFILE_REQUEST_CODE = 888;

  @Override protected int getLayoutResId() {
    return R.layout.fragment_member_vip;
  }

  @Override protected void initPresenter() {
    presenter = new MemberVipPresenter(getActivity(), this, this);
    presenter.init();
  }

  @Override public void initView() {
    mTvTitle.setText("群成员");
    mIdentify = getArguments().getString(ID_KEY);

    mSectionMemberVipInfos = new ArrayList<>();
    mMemberVipInfos = new ArrayList<>();
    mList.setLayoutManager(new LinearLayoutManager(mActivity));
    RecyclerViewDivider.with(mActivity)
        .color(ContextCompat.getColor(mActivity, R.color.windowBackground))
        .size((int) mActivity.getResources().getDimension(R.dimen.line_size))
        .hideLastDivider()
        .build()
        .addTo(mList);
    mAdapter = new SelectMemberVipAdapter(mSectionMemberVipInfos);
    mAdapter.setOnItemClickListener((adapter, view, position) -> {
      if (mSectionMemberVipInfos.get(position).isHeader) return;
      MemberVipInfo info = mSectionMemberVipInfos.get(position).t;
      if (info.getId().equals(MyApplication.getInstance().getThirdAccId())) {
        startFragment(new ProfileFragment());
      } else {
        startFragmentForResult(MemberProfileFragment.create(mSectionMemberVipInfos.get(position).t),
            PROFILE_REQUEST_CODE);
      }
    });
    mList.setAdapter(mAdapter);
    presenter.getGroupMembers(mIdentify);
  }

  @OnClick({ R.id.iv_back, R.id.layout_search }) public void onViewClicked(View view) {
    switch (view.getId()) {
      case R.id.iv_back:
        popBackStack();
        break;
      case R.id.layout_search:
        startFragment(MemberVipSearchFragment.create(mMemberVipInfos));
        break;
    }
  }

  /**
   * 获取群成员VIP等信息完成
   */
  @Override public void getGroupMembersSuc(List<TIMGroupMemberInfo> timGroupMemberInfos,
      List<Map<String, OtherUserInfo>> others) {

    mTvTitle.setText("群成员(" + timGroupMemberInfos.size() + ")");
    mSectionMemberVipInfos.clear();
    mMemberVipInfos.clear();

    List<TIMGroupMemberInfo> infos1 = new ArrayList<>();
    List<TIMGroupMemberInfo> infos2 = new ArrayList<>();
    for (TIMGroupMemberInfo info : timGroupMemberInfos) {
      if (info.getRole() == TIMGroupMemberRoleType.Owner
          || info.getRole() == TIMGroupMemberRoleType.Admin) {
        infos1.add(info);
      } else {
        infos2.add(info);
      }
    }

    if (infos1.size() > 0) {
      // 群主、管理员
      SectionMemberVipInfo memberVipInfo = new SectionMemberVipInfo(true, "群主、管理员");
      mSectionMemberVipInfos.add(memberVipInfo);

      for (TIMGroupMemberInfo info : infos1) {
        MemberVipInfo vipInfo = new MemberVipInfo();
        vipInfo.setId(info.getUser());
        vipInfo.setType(info.getRole());
        vipInfo.setGroupId(mIdentify);
        for (Map<String, OtherUserInfo> map : others) {
          OtherUserInfo otherUserInfo = map.get(info.getUser());
          if (null != otherUserInfo) {
            vipInfo.setName(otherUserInfo.getUser_name());
            if (TextUtils.isEmpty(otherUserInfo.getUser_pic())) {
              vipInfo.setAvatarUrl("");
            } else {
              vipInfo.setAvatarUrl(Api.BASEADDRESS + otherUserInfo.getUser_pic());
            }
            vipInfo.setLevel(otherUserInfo.getUser_level());
            String bir = String.valueOf(otherUserInfo.getCreate_date());
            vipInfo.setCreate_date(DateUtils.strAllTime2Format(bir));
            mMemberVipInfos.add(new SectionMemberVipInfo(vipInfo));
            mSectionMemberVipInfos.add(new SectionMemberVipInfo(vipInfo));
          }
        }
      }
    }

    if (infos2.size() > 0) {
      // 其他成员
      SectionMemberVipInfo memberVipInfo = new SectionMemberVipInfo(true, "其他成员");
      mSectionMemberVipInfos.add(memberVipInfo);
      for (TIMGroupMemberInfo info : infos2) {
        MemberVipInfo vipInfo = new MemberVipInfo();
        vipInfo.setId(info.getUser());
        vipInfo.setType(info.getRole());
        vipInfo.setGroupId(mIdentify);
        for (Map<String, OtherUserInfo> map : others) {
          OtherUserInfo otherUserInfo = map.get(info.getUser());
          if (null != otherUserInfo) {
            vipInfo.setName(otherUserInfo.getUser_name());
            if (TextUtils.isEmpty(otherUserInfo.getUser_pic())) {
              vipInfo.setAvatarUrl("");
            } else {
              vipInfo.setAvatarUrl(Api.BASEADDRESS + otherUserInfo.getUser_pic());
            }
            vipInfo.setLevel(otherUserInfo.getUser_level());
            String bir = String.valueOf(otherUserInfo.getCreate_date());
            vipInfo.setCreate_date(DateUtils.strAllTime2Format(bir));
            mMemberVipInfos.add(new SectionMemberVipInfo(vipInfo));
            mSectionMemberVipInfos.add(new SectionMemberVipInfo(vipInfo));
          }
        }
      }
    }
    mAdapter.notifyDataSetChanged();
  }

  @Override protected void onFragmentResult(int requestCode, int resultCode, Intent data) {
    super.onFragmentResult(requestCode, resultCode, data);

    if (requestCode == PROFILE_REQUEST_CODE) {
      presenter.getGroupMembers(mIdentify);
    }
  }

  @Override public void onResume() {
    super.onResume();
    StatusBarHelper.setStatusBarDarkMode(getActivity());
  }
}
